from rest_framework import serializers, views, status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from apps.app01.models import Address, User


# Address 序列化器
class AddressSerializer(serializers.ModelSerializer):
    class Meta:
        model = Address
        fields = ['id', 'name', 'phone', 'dz']


# 新增地址视图
class AddressCreateView(views.APIView):
    # authentication_classes = []

    def post(self, request):
        # 获取请求中的数据
        data = request.data
        # 获取当前用户对象
        user_id = request.user['user_id']
        user = User.objects.get(id=user_id)
        # user = User.objects.first()

        # 使用序列化器验证并创建新地址
        serializer = AddressSerializer(data=data)
        if serializer.is_valid():
            # 在序列化器保存前手动设置用户对象
            serializer.save(user=user_id)
            return Response(
                {"success": True, "message": "地址添加成功！"},
                status=status.HTTP_201_CREATED
            )
        return Response(
            {"success": False, "message": "地址添加失败！", "errors": serializer.errors},
            status=status.HTTP_400_BAD_REQUEST
        )